package com.m3958.firstgwt.server.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.accesschecker.SectionChecker;
import com.m3958.firstgwt.server.model.Section;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.types.ObjectOperation;

@Singleton
public class NotStandardNeedServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private AppUtilService auservice;
	
	@Inject
	private Injector injector;
	
//	ADD("添加"),FETCH("讀取"),UPDATE("更新"),REMOVE("刪除"),
//	FETCH_CONTENT("獲取內容"),REMOVE_CHILD("刪除子目錄"),	ADD_CHILD("添加子目錄"),	LIST_CHILDREN("列出子目錄"),
//	UPDATE_CONTENT("更新內容"),REMOVE_CONTENT("刪除內容"),ADD_CONTENT("添加內容"),LIST_CONTENT("列出內容"),
//	AUDIT_CONTENT("审核内容");
	
	/**
	 * hasSectionPermission: sectionId,opName
	 */
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		doPost(req, res);
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException {
		String action = req.getParameter("action");
		if("hasSectionPermission".equals(action)){
			processHasSectionPermission(req,res);
		}
	}

	private void processHasSectionPermission(HttpServletRequest req,
			HttpServletResponse res) throws IOException {
		boolean can = false;
		try {
			String sectionId = req.getParameter("sectionId");
			String opName = req.getParameter("opName");
			SectionChecker sc = injector.getInstance(SectionChecker.class);
			can = sc.hasTreeContainerPerms(Section.class.getName(), Integer.parseInt(sectionId), getObOp(opName));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		auservice.writeHtmlResponse(res, String.valueOf(can));
	}
	
	private ObjectOperation getObOp(String name){
		for(ObjectOperation oo:ObjectOperation.values()){
			if(oo.toString().equalsIgnoreCase(name)){
				return oo;
			}
		}
		return null;
	}
}
